#!/usr/bin/env node
const inquirer = require('inquirer')
const path = require('path')
const fs = require('fs')
const ejs = require('ejs')

inquirer
    .prompt([
        {
            type: 'input',
            name: 'name',
            message: 'Project name?',
        },
    ])
    .then((answers) => {
        const root_path = __dirname
        function getAllFiles(root) {
            var res = [],
                files = fs.readdirSync(root)
            files.forEach(function (file) {
                var pathname = root + '/' + file,
                    stat = fs.lstatSync(pathname)

                if (!stat.isDirectory()) {
                    res.push(pathname.replace(root_path, '.'))
                } else {
                    res = res.concat(getAllFiles(pathname))
                }
            })
            return res
        }
        function mkdirsSync(dirname) {
            if (fs.existsSync(dirname)) {
                return true
            } else {
                if (mkdirsSync(path.dirname(dirname))) {
                    fs.mkdirSync(dirname)
                    return true
                }
            }
        }
        const templates = getAllFiles(root_path + '/templates')
        const destDir = process.cwd()
        templates.forEach((file) => {
            ejs.renderFile(
                path.join(__dirname, file),
                answers,
                (err, result) => {
                    if (err) throw err
                    const dirArr = file.split('/')
                    if (dirArr.length > 3) {
                        const newDir = dirArr
                            .slice(2, dirArr.length - 1)
                            .join('/')
                        fs.access(newDir, fs.constants.F_OK, (err) => {
                            if (err) {
                                mkdirsSync(newDir)
                                fs.writeFileSync(
                                    path.join(
                                        destDir,
                                        dirArr.slice(2, dirArr.length).join('/')
                                    ),
                                    result
                                )
                            }
                        })
                    } else {
                        fs.writeFileSync(
                            path.join(
                                destDir,
                                dirArr.slice(2, dirArr.length).join('/')
                            ),
                            result
                        )
                    }
                }
            )
        })
    })
